package com.cnpinxi.service;

import com.cnpinxi.dao.BindDistributorMapper;
import com.cnpinxi.dao.UserMapper;
import com.cnpinxi.domain.BindDistributor;
import com.cnpinxi.domain.User;
import com.cnpinxi.domain.weChat.UserWechatInfo;
import com.cnpinxi.log.LogFactory;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.tool.Tools;
import com.cnpinxi.util.GetProperties;
import com.cnpinxi.util.MD5Tools;
import com.cnpinxi.util.QRCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2017-11-21.
 */
@Service
public class UserServiceImpl implements com.cnpinxi.service.UserService {
    protected Logger logger = LogFactory.getLogger(getClass());
    private final static String RQCODE_URL = "http://www.cnpinxi.com/";
    private final static Integer PROMOTION_AMOUNT = 50;


    /**
     * 分销二维码文件夹
     */
    private final static String COMMISSION = "/commission/";
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatService weChatService;
    @Autowired
    BindDistributorMapper bindDistributorMapper;
private  final  String DEFAULT_PASS_WORD="123456";
    @Override
    public void regedit(User user) {
        User user1 = userMapper.getUserByphone(user);
        if (user1 != null) {
            // throw new MyRunTimeExcption("手机号码已经注册过了！");
            user.setTid(user1.getTid());
            modifyUser(user);
            return;
        }
        if(user.getUserType()==null){
            user.setUserType(User.USER_TYPE_NORMAL);
        }

        String passWord=user.getPassWord();
        if(StringUtils.isBlank(passWord)){
            passWord=DEFAULT_PASS_WORD;
        }
        user.setPassWord(MD5Tools.MD5(passWord));
        if(user.getCreateTime()==null){
            user.setCreateTime(new Date());
        }
        userMapper.insertUser(user);
    }

    @Override
    public User login(User user) {

        user = userMapper.getUser(user);
        if (user == null) {
            throw new MyRunTimeExcption("用户不存在或者密码错误！");
        }
        return user;
    }

    @Override
    public void modifyUser(User user) {

        Long userId=user.getTid();
        if(userId==null){
            regedit(user);
            return;
        }
        userMapper.updateUserByPrimaryKeySelective(user);
    }

    @Override
    public User getUserById(Long userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    public User getUserByPhone(String phone) {
        User user = new User();
        if (StringUtils.isBlank(phone)) {
            return null;
        }
        user.setPhone(phone);
        return userMapper.getUserByphone(user);
    }

    @Override
    public List<User> getUserList(Map<String, String> map) {
        return userMapper.getUserList(map);
    }

    @Override
    public void createSourceQRCode(User user) {
        if (user == null) {
            throw new MyRunTimeExcption("user is null");
        }
        Long tid = user.getTid();

        //生成用户的二维码
        String accessToken = weChatService.getAccessToken();
        UserWechatInfo userWechatInfo = weChatService.getUserWechatInfo(accessToken, user.getOpenId());
        String headImgUrl = userWechatInfo.getHeadimgurl();
        logger.info("微信头像====》》》" + headImgUrl);
        String text = RQCODE_URL + "?activityId=" + tid; // 二维码内容
        String activityName = Tools.getUUID();
        String picPath = GetProperties.readValue("picpath");
        String filePath = picPath + COMMISSION + activityName + ".jpg";
        QRCodeUtil.getLogoQRCode(text, headImgUrl, QRCodeUtil.IMG_FORMAT_JPG, filePath);


        user.setSourceQRCode(COMMISSION + activityName + ".jpg");//二维码图片
        modifyUser(user);
    }

    @Override
    public void bindDistributor(String openId, Long activityId) {

        if (StringUtils.isBlank(openId)) {
            throw new MyRunTimeExcption("openId is null");
        }
        if (activityId == null) {
            throw new MyRunTimeExcption("activityId is null");
        }
        logger.info("通过OPenID查看是否已经bind过。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
        BindDistributor bindDistributor = getBindDistributor(openId);
        if (bindDistributor != null) {
            logger.info("bindDistributor=================>>>>>已经绑定过，不能再次绑定！");
            throw new MyRunTimeExcption("已经绑定过，不能再次绑定！");
        }
        logger.info("没有bind过，继续执行。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");


        User user = getUserById(activityId);
        if (user == null) {
            throw new MyRunTimeExcption("上级没有找到。。。。");
        }
        if (user.getOpenId().equals(openId)) {
            throw new MyRunTimeExcption("不能成为自己的下线！");

        }

        bindDistributor = getBindDistributor(user.getOpenId());
        if (bindDistributor != null) {
            User userParent = getUserById(bindDistributor.getParentId());
            if (userParent.getOpenId().equals(openId)) {
                throw new MyRunTimeExcption("不能成为上级的上级");
            }


        }


        bindDistributor = new BindDistributor();
        bindDistributor.setOpenId(openId);
        bindDistributor.setParentId(activityId);
        bindDistributor.setCreateTime(new Date());
        bindDistributorMapper.insertBindDistributor(bindDistributor);

        promotion(user);


    }

    private void promotion(User user) {

        Map<String, String> map = new HashMap<>();
        map.put("parentId", String.valueOf(user.getTid()));
        List<BindDistributor> bindDistributorList = bindDistributorMapper.selectBindDistributorList(map);

        if (bindDistributorList.size() > PROMOTION_AMOUNT) {
            if (user.getUserType() == User.USER_TYPE_ORGANIZATION) {
                return;
            }
            user.setUserType(User.USER_TYPE_ORGANIZATION);
            modifyUser(user);
        }
    }


    @Override
    public BindDistributor getBindDistributor(String openId) {
        Map<String, String> map = new HashMap<>();
        map.put("openId", openId);
        return bindDistributorMapper.selectBindDistributor(map);
    }

    @Override
    public User getParentUserByopenId(String openId) {
        return userMapper.getParentUserByopenId(openId);
    }
}
